import { useEffect, useImperativeHandle, useState } from "react";
import { Button, Form, Input, InputNumber, Select, Tooltip, Upload } from "antd";
import { UploadOutlined } from '@ant-design/icons';
import { getData } from "utils/ApiUtils";
import { getAllDriverType } from 'api/DriverManagerApi';

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 16 },
};

const DriverForm = ({ ref }) => {
  const [form] = Form.useForm();
  // 将表单实例暴露给父组件
  useImperativeHandle(ref, () => ({
    form
  }))

  const [driverType, setDriverType] = useState([]);
  useEffect(() => {
    // 加载全部驱动类型
    async function fetchAllDriverType() {
      const res = await getAllDriverType();
      setDriverType(res.data);
    }
    fetchAllDriverType();
  }, [])

  /**
   * 驱动包文件上传完成后从上传接口响应中获取文件id塞进表单再提交
   */
  const getLibFileId = e => {
    if (e.file && e.file.response) {
      const res = e.file.response;
      const data = getData(res);
      return data?.id;
    }
    return "";
  }

  const uploadProps = {
    name: 'file',
    method: 'POST',
    action: '/api/driver/lib-upload'    // 文件上传接口
  }

  return (
    <Form
      form={form}
      {...formItemLayout}
      layout="horizontal"
    >

      <Form.Item
        name="name"
        label="名称"
        rules={[
          { required: true, message: '请输入驱动名称' },
          { min: 2, message: '名称至少2个字符' },
        ]}
      >
        <Input placeholder="请输入驱动名称" />
      </Form.Item>

      <Form.Item
        name="version"
        label="版本号"
        rules={[
          { required: true, message: '请输入版本号' },
          { min: 2, message: '名称至少2个字符' },
        ]}
      >
        <Input placeholder="请输入版本号" />
      </Form.Item>

      <Form.Item
        name="type"
        label="驱动类型"
        rules={[
          { required: true, message: '请选择驱动类型' },
          { type: 'string', message: '' },
        ]}
      >
        <Select
          options={driverType}
          placeholder="请选择驱动类型"
        />
      </Form.Item>

      <Form.Item
        name="libFileId"
        label="驱动程序包"
        valuePropName="libFileId"
        getValueFromEvent={getLibFileId}
      >
        <Upload {...uploadProps} listType="picture">
          <Tooltip color="#fff" placement="rightTop" title="请上传.jar格式的文件">
            <Button icon={<UploadOutlined />}>上传</Button>
          </Tooltip>
        </Upload>
      </Form.Item>



    </Form>
  )
}

export default DriverForm;